package regular;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class Ultility {

	public static GraphQuery getAutomaton(Path fileCacheQuery)
			throws IOException {

		FileReader fr = new FileReader(fileCacheQuery.toString());
		BufferedReader br = new BufferedReader(fr);
		String line = "";

		ArrayList<VertexQ> listV = new ArrayList<VertexQ>();

		VertexQ wildcard = null;
		while ((line = br.readLine()) != null) {
			String[] node = line.split("\t");
			VertexQ v = new VertexQ(node[0]);
			for (int i = 1; i < node.length; i++) {
				v.childrenState.add(new EdgeQ(node[i]));
			}

			if (!node[0].equals("_"))
				listV.add(v);
			else
				wildcard = v;
		}
		if (wildcard != null)
			listV.add(wildcard);

		br.close();

		if (listV.size() >= 2) {
			if (wildcard == null)
				return new GraphQuery(listV, listV.get(0), listV.get(listV
						.size() - 1));
			else
				return new GraphQuery(listV, listV.get(0), listV.get(listV
						.size() - 2));
		} else
			return null;

	}

	public static String LOCAL_GRAPH_QUERY = "/home/quyet/test/data1000/graphquery.txt";
	public static String HDFS_GRAPH_QUERY = "/user/quyet/automaton/graphquery.txt";

	public static void cacheGraphQuery(Configuration conf) throws IOException {
		FileSystem fs = FileSystem.get(conf);
		Path hdfsPath = new Path(HDFS_GRAPH_QUERY);

		// upload the file to hdfs. Overwrite any existing copy.
		fs.copyFromLocalFile(false, true, new Path(LOCAL_GRAPH_QUERY), hdfsPath);

		DistributedCache.addCacheFile(hdfsPath.toUri(), conf);
	}

}
